package com.nami.gate.process.upmsg;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.IdUtil;
import com.google.protobuf.ByteString;
import com.nami.gate.cache.TempChannelCache;
import com.nami.gate.config.RpcConfig;
import com.nami.gate.external.basic.constants.UpTopicConst;
import com.nami.gate.middleware.mq.MqSender;
import com.nami.im.network.model.packet.v2.Packet;
import com.nami.transport.proto.codec.MqTransMsg;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.NetUtils;

import java.net.InetSocketAddress;


/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-16 16:41
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class LoginProcess implements PacketProcessor {

    private MqSender mqSender;
    private RpcConfig rpcConfig;

    public LoginProcess(MqSender mqSender, RpcConfig rpcConfig) {
        this.mqSender = mqSender;
        this.rpcConfig = rpcConfig;
    }

    /**
     * from gate service to logic service
     * async
     *
     * @param channel
     * @param packet
     */
    @Override
    public void process(Channel channel, Packet packet) throws Exception {
        TimeInterval timer = DateUtil.timer();
//        String fingerprint = YitIdHelper.nextId() + "";
        // 暂替换为uuid
        String fingerprint = IdUtil.randomUUID();
        log.info("[login] cmd=1 客户端【{}】请求登录, 当前动作指纹:{}", channel.remoteAddress(), fingerprint);
        TempChannelCache.addTempChannel(fingerprint, channel);
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        String clientIp = socketAddress.getAddress().getHostAddress();

        try {
            // 处理方式
            // 1. 发送到router
            // 2. 长连接层直接拼接protobuf二进制流发送到逻辑层

            // 中转router
//            mqSender.send(TopicConst.CONNECT, buildLoginRequest(fingerprint, clientIp, packet));
            // 是否直接发送到业务逻辑服务处理,不走router服务,但是需要处理protubuf二进制流
            mqSender.send(UpTopicConst.LOGIN_TOPIC, buildProtobufLoginBody(fingerprint, clientIp, packet));
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("[login] 发送mq消息失败，", ex.getMessage());
            channel.close();
            return;
//            PacketV2 respPacket = new PacketV2();
//            respPacket.setCmd((byte) CMDEnum.CONNACK.getCode());
//            respPacket.setQos((byte) 0);
//            respPacket.setVersion((byte) 1);
//            String body = """
//                {
//                  "success": false,
//                  "code": 500,
//                  "msg": "系统内部错误！",
//                  "data": ""
//                }
//                """;
//            respPacket.setBody(body.getBytes());
//            channel.writeAndFlush(respPacket);
        }
        log.info("[login] 客户端【{}】请求登录处理完毕。use:{}ms", channel.remoteAddress(), timer.interval());
    }

    private byte[] buildProtobufLoginBody(String fingerprint,
                                          String clientIp,
                                          Packet packet) {
        return MqTransMsg.Gate2LogicLoginRequest.newBuilder()
            .setConnectId(rpcConfig.getConnectId())
            .setDubboIp(NetUtils.getLocalHost())
            .setDubboPort(rpcConfig.getDubboPort())
            .setTempFingerprint(fingerprint)
            .setClientIp(clientIp)
            .setMsg(ByteString.copyFrom(packet.getBody()))
            .build()
            .toByteArray();
    }


}
